package lock2;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo2 {
	public static void main(String[] args) {
		Lock lock = new ReentrantLock();
		AppleOperation operation2 = new AppleOperation(lock,20);
		new Thread(()->{
			int i =0;
			while(true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				operation2.put(++i);
			}
			
		}).start();
		
		
		new Thread(()->{
			while (true) {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				operation2.get();
			}
		}).start();
	}
}

class AppleOperation{
	
	private LinkedList<Integer> list = new LinkedList<>();
	
	private Lock lock ;
	
	private Condition notFull = null;
	
	private Condition notEmpty = null;
	
	private int maxCount = 10;
	
	private int allCount = 0;
	
	private int eatCount = 0;
	
	public AppleOperation(Lock lock,int maxCount) {
		this.lock = lock;
		this.maxCount = maxCount;
		this.notFull = lock.newCondition();
		this.notEmpty = lock.newCondition();
	}
	
	public void put(int obj) {
		lock.lock();
		while(list.size() == maxCount) {
			try {
				System.out.println("放满了....");
				notFull.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		list.add(obj);
		allCount++;
		System.out.println("放了：" + obj+";一共放了：" + allCount);
		notEmpty.signalAll();
		lock.unlock();
	}
	
	public void get() {
		lock.lock();
		while(list.size() == 0) {
			try {
				System.out.println("吃完了....");
				notEmpty.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		eatCount++;
		System.out.println("吃了" + list.removeFirst()+";一共吃了："+ eatCount);
		
		notFull.signalAll();
		lock.unlock();
	}
}

